package services;


import dao.UserDao;
import exception.ActiveUserException;
import exception.LoginException;
import model.User;
import utils.EmailUtils;
import utils.ResponseCode;

import javax.mail.MessagingException;
import java.sql.SQLException;
import java.util.Date;

public class UserService {
    private UserDao userdao= new UserDao();

    public void register(User user) throws MessagingException, SQLException {
            new UserDao().addUser(user);
            String emailMsg = "感谢您注册网上书城，点击"
                    + "<a href='http://localhost:8080/activeUser?activeCode="
                    + user.getActiveCode() + "'>&nbsp;激活&nbsp;</a>后使用。"
                    + "<br />为保障您的账户安全，请在24小时内完成激活操作";
            EmailUtils.emailSend(emailMsg,user.getEmail());
    }

    public User login(User user) throws LoginException {
        //如果登录成功，返回数据库用户记录对应java对象，否则抛出异常：用户没有激活，：用户不存在或者用户密码错误
        User userDB=null;
        try{
            userDB=userdao.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
        }catch (SQLException e){
            e.printStackTrace();
            throw new LoginException(ResponseCode.ERROR_DB);
        }
        if(userDB!=null){
            if(userDB.getState()==1){
                return userDB;
            }else {
                throw new LoginException(ResponseCode.NOT_ACTIVE);
            }
        }else {
            throw new LoginException(ResponseCode.ERROR_NAME_PASSWORD);
        }
    }

    public void active(String activeCode) throws ActiveUserException{
        try {
            User user = userdao.findUserByActiveCode(activeCode);
            if(user==null){
                throw new ActiveUserException(ResponseCode.ERROR_ACTIVE);
            }
            Date registTime=user.getRegistTime();
            long currentTime=System.currentTimeMillis();
            long time=currentTime-registTime.getTime();
            if(time/1000/60/60>24){
                throw new ActiveUserException(ResponseCode.ERROR_EXPIRE);
            }
            userdao.activeUser(activeCode);
        }catch (SQLException e){
            throw new ActiveUserException(ResponseCode.ERROR_DB);
        }
    }
}
